<template>
  <div>
    <div class="top">
      <!--        <el-switch-->
      <!--          v-model="auto_blog"-->
      <!--          active-color="#13ce66"-->
      <!--          inactive-color="#ff4949">-->
      <!--        </el-switch>-->
      <el-select v-model="today_finished" style="width: 200px" placeholder="今日完成状态" size="small" filterable clearable>
        <el-option label="所有" value="" />
        <el-option label="没完成" value="false" />
        <el-option label="完城" value="true" />
      </el-select>
      <el-input
        v-model="kwInput"
        style="width: 400px"
        placeholder="输入 任意字符 进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加站点')"
      >添加站点
      </el-button>
      <el-button
        type="success"
        class="el-icon-folder add-btn"
        :disabled="listLoading"
        style="margin-right: 10px;"
        @click="handleSyncDirectory"
      >同步目录
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
    >

      <el-table-column align="center" width="100" prop="id" label="id" sortable="custom" />

      <el-table-column align="center" label="网址" prop="domain" sortable="custom" width="250" />
      <el-table-column align="center" label="语言" prop="language" sortable="custom" />
      <el-table-column align="center" label="发送" prop="daily_post" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.today_post }}/{{ scope.row.daily_post }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="周期" prop="daily_days" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.daily_days }}天
        </template>
      </el-table-column>
      <el-table-column align="center" label="可发" prop="waiting_send" sortable="custom" />
      <el-table-column align="center" label="写好" prop="waiting_posts" sortable="custom" />
      <el-table-column align="center" label="API类型" prop="api_type" sortable="custom" />
      <el-table-column align="center" label="posts" prop="total_posts" sortable="custom" />
      <!--        <el-table-column align="center" label="待爬" prop="amazon_keywords_remain" sortable="custom">-->
      <!--        </el-table-column>-->
      <!--        <el-table-column align="center" label="佣金账户" prop="amazon_account" sortable="custom">-->
      <!--        </el-table-column>-->
      <!--        <el-table-column align="center" label="佣金tag" prop="amazon_affiliate_tag" sortable="custom">-->
      <!--        </el-table-column>-->

      <!--        <el-table-column align="center" label="AMZ自动博客" prop="amazon_auto_blog" sortable="custom">-->
      <!--          <template slot-scope="scope">-->
      <!--            <el-switch-->
      <!--                @change="handleEdit(scope.row)"-->
      <!--                v-model="scope.row.amazon_auto_blog"-->
      <!--                active-color="#13ce66"-->
      <!--                inactive-color="#ff4949">-->
      <!--            </el-switch>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <el-table-column align="center" label="时间" prop="create_at" sortable="custom" />
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="160px">

        <el-form-item v-if="action !== 'delete'" label="域名">
          <el-input v-model="temp.domain" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="语言">
          <el-select v-model="temp.language" placeholder="语言" filterable>
            <el-option
              v-for="item in languages"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接口类型">
          <el-select v-model="temp.api_type" placeholder="接口类型">
            <el-option label="xmlrpc" value="xmlrpc" />
            <el-option label="restful" value="restful" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="username">
          <el-input v-model="temp.username" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="password">
          <el-input v-model="temp.password" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="daily_post">
          <el-input v-model="temp.daily_post" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="周期">
          <el-input v-model="temp.daily_days" placeholder="请输入内容" style="width: 200px" type="number">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="佣金账户">
          <el-autocomplete
            v-model="temp.amazon_account"
            class="inline-input"
            clearable
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- <el-form-item label="佣金tag" v-if="action !== 'delete'">
            <el-input v-model="temp.amazon_affiliate_tag"></el-input>
          </el-form-item> -->
        <!-- <el-form-item label="自动化类型" v-if="action !== 'delete'">
            <el-autocomplete
            class="inline-input"
            v-model="temp.auto_type"
            :fetch-suggestions="queryAutoType"
            clearable
            placeholder="请输入内容"
          ></el-autocomplete>
          </el-form-item> -->
        <!--          <el-form-item label="项目" v-if="action !== 'delete'">-->
        <!--            <el-select v-model="temp.project_id" placeholder="选择项目">-->
        <!--              <el-option v-for="item in this.projects" :key="item.id" :label=item.name :value=item.id></el-option>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 同步目录弹窗 -->
    <el-dialog
      title="同步目录"
      :visible.sync="syncDirectoryVisible"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="sync-directory-content">
        <div class="top clearfix">
          <el-select
            v-model="selected_webs"
            v-loading="websLoading"
            size="mini"
            placeholder="选择站点"
            clearable
            filterable
            style="width: 90%;"
            @change="handleSelectChange"
          >
            <el-option
              v-for="web in data"
              :key="web.id"
              :label="web.domain"
              :value="web.id"
            />
          </el-select>
          <el-button icon="el-icon-refresh" size="mini" title="刷新" type="info" @click="getList" />
        </div>
        <div v-if="directoryVisible" class="content">
          <wpcategory :account_id="selected_webs" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/cms/wpaccount'
import { Get as GetAmzAccount } from '@/api/cms/amazonaffiliateaccount'
import wpcategory from '@/views/cms/elements/wpcategory'
import qs from 'qs'
// import { Get as GetProjects } from '@/api/erp/elicink/project'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Wpaccounts',
  components: { wpcategory },
  data() {
    return {
      data: [],
      listLoading: false,
      auto_blog: true,
      today_finished: '',
      kwInput: '',
      order_by: 'id',
      order_desc: '1',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      languages: [
        {
          label: '美国英语',
          value: 'en-us'
        },
        {
          label: '日语',
          value: 'ja-jp'
        },
        {
          label: '法语',
          value: 'fr-fr'
        }
      ],
      temp: {
        api_type: 'xmlrpc',
        amazon_auto_blog: false,
        amazon_affiliate_tag: '',
        auto_type: '',
        domain: '',
        language: 'en-us',
        username: '',
        password: '',
        daily_post: 10,
        daily_days: 1,
        project_id: '',
        amazon_account: ''
      },
      width: '',
      projects: [],
      amzaccounts: [],
      innerDialogVisible: false,
      auto_types: [
        { value: 'wp-auto' },
        { value: 'quora-ddg-faq' },
        { value: 'best_amazon' }
      ],
      // 同步目录相关数据
      syncDirectoryVisible: false,
      selected_webs: '',
      websLoading: false,
      directoryVisible: false
    }
  },
  created() {
    // this.handleFetchProjects()
    this.handleGetAmzAccount()
    this.getList()
  },
  methods: {
    queryAutoType(queryString, cb) {
      cb(this.auto_types)
    },
    querySearch(queryString, cb) {
      var amzaccounts = this.amzaccounts
      var results = queryString ? amzaccounts.filter(this.createFilter(queryString)) : amzaccounts
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    resetTemp() {
      this.temp = {
        domain: '',
        api_type: 'xmlrpc',
        username: '',
        password: '',
        project_id: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        project_id: this.$store.getters.projectId,
        today_finished: this.today_finished,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleEdit(row) {
      this.action = 'edit'
      this.temp = Object.assign({}, row)
      this.confirm()
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.domain}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改站点${row.domain}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      _data.project_id = this.$store.getters.projectId
      switch (this.action) {
        case 'create':
          if (_data.project_id === '') {
            alert('必须选择项目')
            return
          }
          if (!_data.domain.length) {
            alert('必须填写域名')
            return
          }
          if (!_data.username.length) {
            alert('必须填写用户名')
            return
          }
          if (!_data.password.length) {
            alert('必须填写密码')
            return
          }
          Post({
            domain: _data.domain,
            username: _data.username,
            api_type: _data.api_type,
            password: _data.password,
            daily_post: _data.daily_post,
            language: _data.language,
            daily_days: _data.daily_days,
            amazon_auto_blog: _data.amazon_auto_blog,
            amazon_account: _data.amazon_account,
            amazon_affiliate_tag: _data.amazon_affiliate_tag,
            auto_type: _data.auto_type,
            project_id: _data.project_id

          }
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, {
            domain: _data.domain,
            username: _data.username,
            password: _data.password,
            daily_post: _data.daily_post,
            api_type: _data.api_type,
            daily_days: _data.daily_days,
            language: _data.language,
            amazon_auto_blog: _data.amazon_auto_blog,
            amazon_account: _data.amazon_account,
            amazon_affiliate_tag: _data.amazon_affiliate_tag,
            auto_type: _data.auto_type,
            project_id: _data.project_id
          }).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeWebDialog', false)
    },
    // handleFetchProjects() {
    //   GetProjects()
    //     .then(response => {
    //       this.projects = response.data.data
    //     })
    //     .catch(e => {
    //       console.log('error')
    //     })
    // },
    handleGetAmzAccount() {
      GetAmzAccount()
        .then(response => {
          this.amzaccounts = response.data.data.map(v => {
            return { value: v.username }
          })
        })
        .catch(e => {
          console.log('error')
        })
    },
    // 同步目录相关方法
    handleSyncDirectory() {
      this.syncDirectoryVisible = true
      this.selected_webs = ''
      this.directoryVisible = false
    },
    handleSelectChange() {
      console.log(this.selected_webs)
      if (this.selected_webs > 0) {
        this.directoryVisible = true
      } else {
        this.directoryVisible = false
      }
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin-top: 60px;
    /*margin: 168px auto !important;*/
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }

  .sync-directory-content {
    min-height: 400px;
  }

  .sync-directory-content .top {
    margin-bottom: 20px;
    padding: 10px;
    border-bottom: 1px solid #eee;
  }

  .sync-directory-content .content {
    padding: 10px;
  }
</style>
